/* eslint-disable react/prop-types */

import React, { Component } from 'react';

export default class LoginComponent extends Component {
  constructor(props, context) {
    super(props, context);
    this.handleLogin = this.handleLogin.bind(this);
    this.login(this.props.location && this.props.location.query.code);
  }

  login(code) {
    const { actions, router } = this.props;
    const { fetchToken, me } = actions;
    if (code) {
      fetchToken({
        code,
      }).then(token => me(token)).then(() => {
        const returnUrl = window.localStorage.getItem('HyperVerse_ReturnUrl');
        window.location.href = router.createHref(returnUrl || '/');
      });
    }
  }

  handleLogin(e) {
    e.preventDefault();
    e.stopPropagation();

    const returnUrl = this.props.location.query.returnUrl || '/';
    window.localStorage.setItem('HyperVerse_ReturnUrl', returnUrl);
    this.props.actions.login();
  }

  render() {
    return !this.props.location.query.code && (
      <div>
        <p>Please login to continue</p>

        <button onClick={this.handleLogin}>
          login
        </button>

        <div />
      </div>
    );
  }
}
